package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.ExcelUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dao.OrdersDto;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.util.UUID;


@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    OrderDetailService orderDetailServicel;


    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize) {
        //分页构造器
        Page<OrdersDto> page2 = new Page<>(page, pageSize);
        Page<Orders> page1 = new Page<>(page, pageSize);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(page1,queryWrapper);


        BeanUtils.copyProperties(page1, page2, "records");

        List<Orders> records = page1.getRecords();
        List<OrdersDto> records2 = new ArrayList<>();


        records.forEach(orders -> {

            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);

            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> list = orderDetailServicel.list(queryWrapper1);


            ordersDto.setPhone(orders.getPhone());
            ordersDto.setAddress(orders.getAddress());
            ordersDto.setConsignee(orders.getConsignee());
            ordersDto.setOrderDetails(list);


            records2.add(ordersDto);


          //  System.out.println(ordersDto);
        });

        page2.setRecords(records2);
       // System.out.println("22222222222222222222222222222222222222222222222222");
        return R.success(page2);
    }


    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {


//        当前用户的购物车列表
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

//                订单号生成
        //UUID生产纯数字
        orders.setNumber(String.valueOf(IdWorker.getId()));

//                获得购物车订单总价格
        BigDecimal bigDecimal = new BigDecimal("0");

        for (ShoppingCart shoppingCart : list) {

            Integer number = shoppingCart.getNumber();
            BigDecimal amount = shoppingCart.getAmount();
            BigDecimal multiply = amount.multiply(BigDecimal.valueOf(number));
            bigDecimal = bigDecimal.add(multiply);

        }


//        获得用户下单地址
        LambdaQueryWrapper<AddressBook> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AddressBook::getId, orders.getAddressBookId());
        AddressBook one = addressBookService.getOne(queryWrapper1);


//                设置订单的基本属性
        orders.setAddress(one.getDetail());   //地址
        orders.setUserId(BaseContext.getCurrentId());  //用户id
        orders.setStatus(2);                            //状态码
        orders.setOrderTime(LocalDateTime.now());       //下单时间
        orders.setCheckoutTime(LocalDateTime.now());    //结账时间
        orders.setPhone(one.getPhone());              //用户手机号码
        orders.setConsignee(one.getConsignee());       //收货人
        orders.setAmount(bigDecimal);                  //金额

        orderService.save(orders);


//                订单明细
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
//        购物车循环设置订单明细表：
        list.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());   //订单id
            orderDetail.setName(shoppingCart.getName());  //名字
            orderDetail.setImage(shoppingCart.getImage());  //图片
            orderDetail.setNumber(shoppingCart.getNumber());     //设置数量
            orderDetail.setAmount(shoppingCart.getAmount());  //设置单个的价格
            if (shoppingCart.getSetmealId() != null) {              // 如果套餐id不等空
                orderDetail.setDishId(shoppingCart.getSetmealId());  //那么添加套餐 id
            } else {
                orderDetail.setDishId(shoppingCart.getDishId()); //添加菜品id
                orderDetail.setDishFlavor(shoppingCart.getDishFlavor()); //添加菜品口味
            }

            System.out.println(orderDetail.getOrderId()+"---->"+orders.getId());
            orderDetails.add(orderDetail);
        });
//                删除购物车
        shoppingCartService.remove(queryWrapper);
//                添加订单明细
        orderDetailServicel.saveBatch(orderDetails);

        return R.success("成功");
    }




    @GetMapping("/page")
    public R<Page<Orders>> userPage1(int page, int pageSize, Long number, String beginTime, String endTime) throws ParseException {
        //构造分页
        Page<Orders> page1 = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //根据时间进行排序
       queryWrapper.orderByDesc(Orders::getOrderTime);

       //判断订单号是否为空
       if (number!=null){
        queryWrapper.eq(Orders::getNumber,number);
       }

       //判断查询时间是否为空
       if (beginTime!=null &&  endTime!=null){
           SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           Date beginDate = sdf.parse(beginTime);
           Date endDate = sdf.parse(endTime);
            queryWrapper.between(Orders::getOrderTime,beginDate,endDate);
       }

       orderService.page(page1,queryWrapper);


        return R.success(page1);
    }



    @PutMapping()
    public R<String> updata(@RequestBody Orders orders){

        orderService.updateById(orders);


        return R.success("成功");
    }
    
    
    
    @GetMapping("/export")
    public void   export(HttpServletResponse response){
        List<Orders> list = orderService.list();
        System.out.println(list);

        ExcelUtils.exportExcel(list,"用户信息","sheet1",Orders.class,"testDATA.xlsx",response);
    }
}
